/******************************************************************************
 * @File name   :      MaintainMasterDataController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 15, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 15, 2015 11:38:08 AM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.masterdata.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cap.bts.crmdp.dealer.card.util.FileUtil;
import com.cap.bts.crmdp.dealer.logistic.constants.FileType;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.masterdata.dto.DataFixPrcResultDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerChangeDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerQueryDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DealerResultsDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DmsDataFixResultDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.DmsDateFixDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.MaintainMasterDataSubmitDto;
import com.cap.bts.crmdp.dealer.masterdata.dto.SmsSendDto;
import com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService;
import com.cap.bts.crmdp.dealer.member.dto.MemberExportDto;
import com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto;
import com.cap.bts.crmdp.dealer.member.service.IMaintainCarPlateService;
import com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.Utils;

/**
 * MaintainMasterDataController
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/masterdata")
public class MaintainMasterDataController extends BaseController {

	static final String GETMAINTAINDEALERPAGE = "getMaintainDealerPage";
	static final String DEALERRESULTSDTOLIST = "dealerResultsDtoList";
	private static final Logger LOGGER = Logger.getLogger(MaintainMasterDataController.class);
	@Autowired
	IMaintainDealerService maintainDealerService;

	@Autowired
	ICodeMapping codeMappingService;
	
	@Autowired
    IMaintainMemberService maintainMemberService;
	
	@Autowired
    IMaintainCarPlateService maintainCarPlateService;
	
	@Autowired
    private MessageSource messageSource;
	/**
	 * 维护经销商首页查询
	 * 
	 * @Date : 2015-7-15
	 * @param dto
	 *            DealerQueryDto
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping(value = "/toMaintainDealerPage")
	public String toMaintainDealerPage(DealerQueryDto dto, Model model, HttpServletRequest request) throws AppException {
		model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
		model.addAttribute("dto", dto);
		return "/masterdata/maintainDealer";
	}

	/**
	 * 维护经销商查询页
	 * 
	 * @Date : 2015-7-15
	 * @param dto
	 *            DealerQueryDto
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping(value = "/getMaintainDealerPage")
	public String getMaintainDealerPage(DealerQueryDto dto, Model model, HttpServletRequest request) throws AppException {


		List<DealerResultsDto> dealerResultsDtoList = new ArrayList<DealerResultsDto>();

		if (dto != null) {
			dto.setId(null);
			dealerResultsDtoList = maintainDealerService.getMaintainDealerByDto(dto);
			for (DealerResultsDto dealerResultsDto : dealerResultsDtoList) {
			    dealerResultsDto.setDealerStatus(
			        CodeTextUtils.getText("MasterDataDealerInfo.DealerStatus", dealerResultsDto.getDealerStatus()));
			    dealerResultsDto.setDealerProgram(
			        CodeTextUtils.getText("MasterDataDealerInfo.DealerProgram", dealerResultsDto.getDealerProgram()));
			    dealerResultsDto.setRegion(
			        CodeTextUtils.getText("MasterDataDealerInfo.DealerRegion", dealerResultsDto.getRegion()));
            }
			model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
		}
		request.getSession().setAttribute(GETMAINTAINDEALERPAGE, dto);
		model.addAttribute(DEALERRESULTSDTOLIST, dealerResultsDtoList);
		model.addAttribute("dto", dto);
		return "/masterdata/maintainDealer";
	}

	/**
	 * 转向新增经销商页面
	 * 
	 * @Date : 2015-7-16
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws AppException
	 */
	@RequestMapping(value = "/toCreateDealerPage")
	public String getcreateDealerPage(Model model, HttpServletRequest request) throws AppException {

		MaintainMasterDataSubmitDto maintainMasterDataSubmitDto = new MaintainMasterDataSubmitDto();
		model.addAttribute("submitDto", maintainMasterDataSubmitDto);

		String dealerId = request.getParameter("id");
		if (Utils.notEmpty(dealerId)) {
			model.addAttribute("id", dealerId);

			DealerQueryDto dto = new DealerQueryDto();

			dto.setId(Long.getLong(dealerId));

			model.addAttribute(DEALERRESULTSDTOLIST, maintainDealerService.getMaintainDealerByDto(dto));
			model.addAttribute("dto", dto);

		}

		return "/masterdata/createDealer";

	}

	/**
	 * 转向新增经销商页面
	 * 
	 * @Date : 2015-7-16
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws AppException
	 */
	@RequestMapping(value = "/toEditDealerPage")
	public String geteditDealerPage(Model model, HttpServletRequest request) throws AppException {

		MaintainMasterDataSubmitDto maintainMasterDataSubmitDto = new MaintainMasterDataSubmitDto();
		model.addAttribute("submitDto", maintainMasterDataSubmitDto);

		String dealerId = request.getParameter("id");
		if (Utils.notEmpty(dealerId)) {
			model.addAttribute("id", dealerId);

			DealerQueryDto dto = new DealerQueryDto();

			dto.setId(Long.valueOf(dealerId));

			model.addAttribute(DEALERRESULTSDTOLIST, maintainDealerService.getMaintainDealerByDto(dto));
			model.addAttribute("dto", dto);

		}

		return "/masterdata/editDealer";

	}

	/**
	 * 保存经销商 信息
	 * 
	 * @Date : 2011-7-6
	 * @param mDealerSubmitDto
	 *            MaintainMasterDataSubmitDto
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws AppException
	 * @throws IOException
	 */
	@RequestMapping(value = "/saveOrUpdateDealer")
	public String submitToSaveOrUpdateDealer(MaintainMasterDataSubmitDto mDealerSubmitDto, Model model,
			HttpServletRequest request) throws AppException {
		try {
			maintainDealerService.saveDealer(mDealerSubmitDto);
		} catch (AppException e) {
			throw e;
		}
		DealerQueryDto queryDto = new DealerQueryDto();
		if(Utils.notNullAndNegative(mDealerSubmitDto.getId())){
			 Object queryDtoObject=request.getSession().getAttribute(GETMAINTAINDEALERPAGE);
		     if(queryDtoObject!=null){
		     	queryDto=(DealerQueryDto)queryDtoObject;
		     }
			
		}

		return getMaintainDealerPage(queryDto, model, request);
	}
	
	@RequestMapping(value = "/updateDealerAndCarplate")
	@ResponseBody
	public boolean updateDealerAndCarplate(MemberResultsDto memberResultsDto, Model model,
	    HttpServletRequest request) throws AppException {
	    try {
	        
	        return maintainMemberService.updateMemberNameByMemberResultsDto(memberResultsDto);
	    } catch (AppException e) {
	        throw e;
	    }
	}
	

	@RequestMapping(value = "/toExportMemberAndPackageInfo")
	public String toExportMemberAndPackageInfo(MemberExportDto memberExportDto, Model model) throws AppException {
		model.addAttribute("memberExportDto", memberExportDto);
		return "/member/exportMemberAndPackageInfo";
	}
	
	@RequestMapping(value = "/checkMemberExist")
	@ResponseBody
	public boolean checkMemberExist(MemberExportDto memberExportDto, Model model) throws AppException {
		if(memberExportDto != null){
			String dealerNum = memberExportDto.getDealerNum();
			MasterDataDealerInfo dealer = maintainDealerService.getDealerByDealerNum(dealerNum);
			if(dealer != null){
				return true;
			}
		}
		return false;
	}
	
	@RequestMapping(value = "/exportMember")
	public String exportMember(MemberExportDto memberExportDto, Model model,
			HttpServletRequest request, HttpServletResponse response) throws AppException {
		try {
			if(memberExportDto != null){
				String dealerNum = memberExportDto.getDealerNum();
				File memberFile = maintainDealerService.exportMemberFromDealer(dealerNum);
				if(memberFile != null){
					FileUtil.downloadZip(memberFile,response,request,"GBK","GBK");
				}
			}
		} catch (Exception e) {
			throw new AppException("exportMember",e);
		}
		return "/member/exportMemberAndPackageInfo";
	}
	
	@RequestMapping(value = "/exportPortfolio")
	public String exportPortfolio(MemberExportDto memberExportDto, Model model,
			HttpServletRequest request, HttpServletResponse response) throws AppException {
		try {
			if(memberExportDto != null){
				String dealerNum = memberExportDto.getDealerNum();
				File portfolioFile = maintainDealerService.exportPortfolioFromDealer(dealerNum);
				if(portfolioFile != null){
					FileUtil.downloadZip(portfolioFile,response,request,"GBK","GBK");
				}
			}
		} catch (Exception e) {
			throw new AppException("exportPortfolio",e);
		}
		return "/member/exportMemberAndPackageInfo";
	}
	
	@RequestMapping(value = "/toDealerChange")
	public String toDealerChange(DealerChangeDto dealerChangeDto, Model model) throws AppException {
		List<DealerChangeDto> list = maintainDealerService.getAllDealerChange(dealerChangeDto);
		model.addAttribute("dealerChangeDtoList", list);
		model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dealerChangeDto.getPager());
		return "/member/dealerChange";
	}
	
	@RequestMapping(value = "/updateDealerChange")
	@ResponseBody
	public boolean updateDealerChange(String dealerNum,String changeDate, Model model) throws AppException {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date date = dateFormat.parse(changeDate);
			SimpleDateFormat dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String changeDateString = dateString.format(date);
			return maintainDealerService.updateChangeTimeFromDealerChange(dealerNum, changeDateString);
		} catch (ParseException e) {
			throw new AppException("updateDealerChange", e);
		}
	}
	
	@RequestMapping(value = "/toAddDealerChange")
	public String toAddDealerChange(DealerChangeDto dealerChangeDto, Model model) throws AppException {
		model.addAttribute("dealerChangeDto", dealerChangeDto);
		return "/member/addDealerChange";
	}
	
	@RequestMapping(value = "/checkDealerExisted")
	@ResponseBody
	public boolean checkDealerExisted(DealerChangeDto dealerChangeDto, Model model) throws AppException {
		if(dealerChangeDto != null){
			if(StringUtils.isNotBlank(dealerChangeDto.getDealerNum())){
				return maintainDealerService.checkDealerExisted(Long.parseLong(dealerChangeDto.getDealerNum()));
			}
		}
		return false;
	}
	
	@RequestMapping(value = "/saveDealerChanged")
	@ResponseBody
	public boolean saveDealerChanged(DealerChangeDto dealerChangeDto, Model model) throws AppException {
		if(dealerChangeDto != null){
			try {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = dateFormat.parse(dealerChangeDto.getChangeDate());
				SimpleDateFormat dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String changeDateString = dateString.format(date);
				dealerChangeDto.setChangeDate(changeDateString);
				return maintainDealerService.saveDealerChanged(dealerChangeDto);
			} catch (ParseException e) {
				throw new AppException("saveDealerChanged", e);
			}
		}
		return false;
	}
	
    
    //转向汉得DMS数据修复界面
    @RequestMapping(value = "/toDataFixPage")
    public String toDataFixPage(Model model, HttpServletRequest request) throws AppException {
        DmsDateFixDto dto = new DmsDateFixDto();
        model.addAttribute("dto", dto);
        model.addAttribute("uploadResult", false); 
        model.addAttribute("suc", true);
        return "/member/uploadDMSPackageInfo";
    }
    
    /**
     * 处理上传数据
     */
    @RequestMapping(value = "/uploadDataFixPage")
    public String uploadDataFixPage(@ModelAttribute("dto")DmsDateFixDto dmsDateFixDto,
              Model model) {
    	List<DmsDataFixResultDto> result = new ArrayList<DmsDataFixResultDto>();
        try {
          MultipartFile file = dmsDateFixDto.getDmsDateFixFile();
          if(file==null  || file.getSize()<=0){
              dmsDateFixDto.setErrorMsg(messageSource.getMessage("excel.file.notEmpty",null, Locale.CHINA));
          }else if(!file.getOriginalFilename().endsWith(FileType.XLS.getValue())&& 
                  !file.getOriginalFilename().endsWith(FileType.XLSX.getValue())){
              dmsDateFixDto.setErrorMsg(messageSource.getMessage("excel.file.type", null, Locale.CHINA));
          }else{ 
              result = maintainDealerService.handleImportInBackground(file.getOriginalFilename(), 
                  file.getInputStream() ,"DMS_datafix_template_items.xml", "dmsDateFixTemplateItems","DmsReport");
              model.addAttribute("fileName", file.getOriginalFilename());
              
              if(result != null && !result.isEmpty()){
                    model.addAttribute("uploadResult", true); 
                    model.addAttribute("suc", true);
                    //调用存储过程
                    DataFixPrcResultDto dto = maintainDealerService.prcDmsDataFix();
                    model.addAttribute("dataFixPrcResultDto",dto);
                } else {
                    model.addAttribute("uploadResult", true);
                    model.addAttribute("suc", false);
                }
              
          }
        } catch (Exception e) {   
            model.addAttribute("uploadResult", false);
            model.addAttribute("suc", false);
            LOGGER.error(e);
        }               
        return "/member/uploadDMSPackageInfo";
    }
    
    @RequestMapping(value = "/toSendMessage")
    public String toSendMessage(Model model) throws AppException {
		return "sms/sms_send";
	}
    
    //手动发送短信(对应tm_sms_send)
    @RequestMapping(value = "/sendMessage")
	@ResponseBody
	public boolean sendMessage(Model model) throws AppException {
    	boolean result = false;
		try {
			List<SmsSendDto> smsList = maintainDealerService.getAllMessageForSend();
			if(smsList != null &&!smsList.isEmpty()){
				result = maintainDealerService.sendMessage(smsList);
			}
		} catch (Exception e) {
			throw new AppException("saveDealerChanged", e);
		}
		return result;
	}
}
